// pages/circleSet/circleSet.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
import { jump } from "../../utils/utils"
import { uploadAliyun } from '../../utils/UploadAliyun';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    circleId:'', //圈子id
    info: {}, //详情数据
    form: {}, //表单数据

    showIdentityList: false ,//收起、展开用户身份
    // 修改圈子名称
    circleName: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      circleId: options?.circleId
    }, () => {
      this.getInfo()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.quitModal = this.selectComponent('#quit-modal')
    this.closeModal = this.selectComponent('#close-modal')
    this.auditModal = this.selectComponent('#audit-modal')
    this.sheet = this.selectComponent('#sheet')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  // 获取详情数据
  async getInfo() {
     const { circleId } = this.data
      if (!circleId) return
      const res = await request.get(api.circleDetail, { id: circleId }, { loading: false })
      if (res.data.addTime) {
        res.data.addTime = res.data.addTime?.split(' ')[0]?.replace(/[-]/g, '/')
      }
      this.setData({
        info: {
          ...res?.data,
        }
      })
      let form=JSON.parse(JSON.stringify(this.data.info))
      let identityStr=[]
      form.identityList=[
        {label: '星选官',value: 99,checked: false},
        {label: '普通用户',value: 1, checked: false},
        {label: '督导员',value: 2,checked: false},
        {label: '内部员工',value: 3,checked: false},
        {label: '地推兼职',value: 4,checked: false},
        {label: '仓管',value: 5,checked: false},
        {label: '官方',value: 6,checked: false},
      ]
      if(form.userIdentity){
          form.userIdentity.split(',').forEach(item=>{
          form.identityList.forEach(subItem=>{
              if(subItem.value==item){
                subItem.checked=true
                identityStr.push(subItem.label)
              }
          })
        })
      }
      form.identityStr=identityStr.join(',')
      this.setData({
         form,
         identityStr
      })
  },
  //上传头像
  uploadImg(){
  // 是圈主，并且有修改资料权限
  if(this.data.info.owner && this.data.info.dataEdit===0){ 
    wx.chooseImage({
      count: 1,
      success: (img) => {
        const [imgData] = img?.tempFiles || [{}]
        console.log(imgData);
        if (!imgData) {
          wx.showToast({
            icon: 'none',
            title: '没有获取到图片数据',
          })
          return
        }
       wx.getImageInfo({
        src: img.tempFilePaths[0],
        success: (res) => {
        if (['jpg', 'jpeg', 'png'].every(item => !imgData?.path?.endsWith(item))) {
          wx.showToast({
            icon: 'none',
            title: '仅支持jpg、png、jpeg类型的图片',
          })
          return
        }
        if ((+imgData?.size / 1024 / 1024) > 2) {
          wx.showToast({
            icon: 'none',
            title: '仅支持小于2M的图片',
          })
          return
        }
        // 限制宽高
        if(res.width> 375 || res.height> 315){ 
          wx.showToast({
            icon: 'none',
            title: '仅支持宽小于等于375像素、高小于等于315像素的图片',
          })
          return
        }
        uploadAliyun(
          img.tempFilePaths[0],
          (picPath) => {
            if (picPath) {
              this.setData({
                ['form.image']: picPath
              })
            }
          },
          { directory: 'kejian-space/' }
        )
      },
    })
    }
   })
   }
  },
  // 跳转圈子名称修改
  nameHandle(){
    jump('circleTitleSet', {
      circleId: this.data.circleId,
      title: encodeURIComponent(this.data.form.title || ''),
      auth: this.data.info.owner && this.data.info.dataEdit===0 
    })
 },
  // 跳转圈子简介修改页面
  descHandle(){
     jump('circleDescSet', {
        circleId: this.data.circleId,
        remark:encodeURIComponent(this.data.form.remark || ''),
        auth: this.data.info.owner && this.data.info.dataEdit===0 
      })
  },
  //跳转圈子成员页面
  jumpCircleMember(){
     jump('circleMember', {circleId: this.data.circleId})
  },
  //收起、展开用户身份
  toggleIdentity(){
    // 是圈主并且有权限
    if(this.data.info.owner && this.data.info.userIdentityEdit===0){
      this.setData({
        showIdentityList: !this.data.showIdentityList
      })
    }
  },
  // 可入圈用户身份改变
  identityChange(e){
    let items = this.data.identityList
    const currentValue = e.currentTarget.dataset.value

    items = items.map(item => {
      if (item.value === currentValue) {
        item.checked = !item.checked
      }
      return item
    })
  
    this.setData({
      identityList: items,
    })
  },
  // 可入圈用户身份改变确认
  identityConfrim(){
    let items = this.data.identityList
    const identityStr = []
    const identityIds = []

    items = items.map(item => {
      if (item.checked) {
        identityStr.push(item.label)
        identityIds.push(item.value)
      }
      return item
    })
    this.setData({
      ['form.identityList']: items,
      ['form.userIdentity']: identityIds.join(','),
      ['form.identityStr']: identityStr.join(','),
      identityStr
    })
    this.hideSheet()
  },
  // 是否公开操作
  isOpenChange(e){
   if(!e.detail.value){
    this.closeModal.show()
    return
   }
    this.setData({
      ['form.open']: e.detail.value? 0 : 1 
    })
  },
  // 关闭公开确定
  closeConfirm(){
    this.setData({
      ['form.open']: 1
   })
   this.closeModal.hide()
  },
  // 取消公开确定
  calcelConfirm(){
    this.setData({
      ['form.open']: 0
   })
  },
  // 是否需要审核操作
  isAuditChange(e){
    if(!e.detail.value){
      this.auditModal.show()
      return
     }
    this.setData({
      ['form.audit']: e.detail.value? 0 : 1 
    })
  },
  // 关闭审核确定
  auditConfirm(){
    this.setData({
      ['form.audit']: 1
    })
    this.auditModal.hide()
  },
  // 取消审核确定
  auditClose(){
    this.setData({
      ['form.audit']: 0
    })
  },
  
  //保存
  async saveConfirm(){
    if (this.loading) return
    this.loading = true
    let {image, title, remark, userIdentity, open, audit, userId}= this.data.form
    if(userIdentity === ''){
     wx.showToast({
       title: '可入圈的用户身份不能为空',
       icon: 'none'
     })
     this.loading = false
      return
    }
    let params={
      image,
      title,
      remark,
      userIdentity,
      open,
      audit,
      userId,
      id: this.data.circleId
    }
    let res=await request.post(api.circleUpdate,params,{loading: true})
    if (res.httpStatus === 200) {
      wx.showToast({
        icon: 'none',
        title: '保存成功',
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 800)
    }
    this.loading = false
  },
  //退出圈子操作
  quitHandle(){
    this.quitModal.show()
  },
  //退出圈子确定
  async quitConfirm(){
    if (this.loading) return
    this.loading = true
    const res = await request.post(api.circleQuit + '/' + this.data.circleId, null, { loading: false })
    if (res.httpStatus === 200) {
      setTimeout(() => {
        wx.showToast({
          icon: 'none',
          title: res.data,
        })
      })
      this.quitModal.hide()
      wx.navigateBack({
        delta: 2
      })
    }
    this.loading = false
  },
  // 打开操作弹窗
  showSheet() {
    // 是圈主并且有权限
    if(this.data.info.owner && this.data.info.userIdentityEdit === 0){
      const identityList = JSON.parse(JSON.stringify(this.data.form.identityList))
      this.setData({
        identityList
      })
      this.sheet.show()
    }
  },
  // 关闭操作弹窗
  hideSheet() {
    this.setData({
      identityList: null
    })
    this.sheet.hide()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    return shareOptions('default', e)
  }
})